package com.jiangxjsy.admin.support;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import com.jiangxjsy.admin.service.AdminDeptService;
import com.jiangxjsy.admin.service.AdminUserRoleService;
import com.jiangxjsy.admin.service.AdminUserService;
import com.jiangxjsy.core.constant.BasicConstant;
import com.jiangxjsy.core.redis.Redis;
import com.jiangxjsy.core.system.SystemCore;
import com.jiangxjsy.model.admin.entity.AdminUser;
import com.jiangxjsy.model.admin.vo.AdminUserVO;
import com.jiangxjsy.model.admin.vo.DeptVO;
import com.jiangxjsy.model.core.entity.UserExtra;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * wukong-crm-master
 * 蒋胜宇
 * 2025/6/7 18:21
 */

@Component
public class AdminUserSupport {
    @Resource
    private Redis redis;

    @Resource
    private AdminUserRoleService adminUserRoleService;

    @Resource
    private AdminUserService adminUserService;

    @Resource
    private AdminDeptService adminDeptService;

    /**
     * 获取用户 token
     *
     * @param type 登录类型
     * @param userId 用户 id
     * @return userToken
     */
    public String getUserToken(Integer type, Long userId){
        return BasicConstant.USER_TOKEN + ":" + type + ":" + userId.toString();
    }

    /**
     * 用户退出
     *
     * @param userId 用户 id
     * @param type 登录类型
     */
    public void userExit(Long userId, Integer type) {
        if (type == null) {
            for (Integer integer : Arrays.asList(1, 2, 3, 4)) {
                userExit(userId, integer, null);
            }
        } else {
            userExit(userId, type, null);
        }

    }

    /**
     * 用户退出
     *
     * @param userId 用户 id
     * @param type 登录类型
     * @param extra 额外信息，1 代表被挤掉提示
     */
    public void userExit(Long userId, Integer type, Integer extra) {
        String token = null, key = getUserToken(type, userId);
        if (redis.hasKey(key)) {
            token = redis.get(String.class, key);
            redis.delete(key);
        }

        if (Objects.equals(1, extra) && token != null) {
            Long time = redis.ttl(token);
            if (time > 1L) {
                redis.setEx(token, new UserExtra(1, DateUtil.formatDateTime(new Date())), time.intValue(), TimeUnit.MINUTES);
            }
        } else {
            if (token != null) {
                redis.delete(token);
            }
        }
    }

    /**
     * 判断是否是管理员
     *
     * @param userId 用户 id
     * @return true 是管理员
     */
    public boolean isAdmin(Long userId) {
        return SystemCore.getSuperUser().equals(userId) ||
                adminUserRoleService.queryUserRoleIds(userId).contains(SystemCore.getSuperRole());
    }

    /**
     * 获取父级名称
     *
     * @param parentId 父级 id
     * @return 父级名称
     */
    public String getParentName(Long parentId) {
        if (parentId == null) {
            return "";
        }
        AdminUser adminUser = adminUserService.queryByUserId(parentId);
        if (adminUser == null) {
            return "";
        }
        return adminUser.getRealname();
    }

    /**
     * 转换用户信息为 VO 对象
     *
     * @param adminUser 用户信息
     * @param userIdentity 用户身份
     * @return 用户信息 VO
     */
    public AdminUserVO convertAdminUserToVO(AdminUser adminUser, Integer userIdentity) {
        AdminUserVO userVO = BeanUtil.copyProperties(adminUser, AdminUserVO.class);
        userVO.setUserIdentity(userIdentity);
        userVO.setDeptName(adminDeptService.getNameByDeptId(Long.valueOf(userVO.getDeptId())));
        return userVO;
    }

    /**
     * 创建部门树
     *
     * @param pid 上级部门 id
     * @param deptList 部门列表
     * @return 部门树
     */
    public List<DeptVO> createTree(int pid, List<DeptVO> deptList) {
        List<DeptVO> treeDept = new ArrayList<>();
        for (DeptVO dept : deptList) {
            if (pid == dept.getPid()) {
                treeDept.add(dept);
                List<DeptVO> children = createTree(dept.getDeptId(), deptList);
                if (CollUtil.isNotEmpty(children)) {
                    for (DeptVO child : children) {
                        dept.setAllNum(dept.getAllNum() + child.getAllNum());
                    }
                    dept.setHasChildren(1);
                } else {
                    dept.setHasChildren(0);
                }
            }
        }
        return treeDept;
    }
}
